package com.gla.market.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gla.market.R;
import com.gla.market.constant.Constants;
import com.gla.market.entity.AddressItem;
import com.gla.market.entity.Commodity;
import com.gla.market.utils.NetUtil;
import com.gla.market.utils.SharedPreferencesUtil;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UpdateAddressActivity extends AppCompatActivity implements TencentLocationListener {
    EditText update_getman2,update_phone2,update_area2,update_name2;
    Button update_back,update_save,update_delete;
    ImageButton update_location;
    CheckBox update_default;

    AddressItem addressItem;
    int id,user_id;
    int flag;
    String addressArea,addressName;

    private Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_address);
        Intent intent = getIntent();
        //得到用户的名字
        addressItem = (AddressItem)intent.getSerializableExtra("userAddress");
        Log.d("userinformation",addressItem.toString());
        initView();
        //返回按钮
        update_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                finish();
            }
        });
        //修改保存按钮
        update_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UpAddress();
            }
        });
        //删除按钮
        update_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Delete();
            }
        });
        //定位按钮
        update_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getLocation();
            }
        });
        //设为默认地址按钮
        update_default.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    flag = 1;
                }else{
                    flag =0;
                }
            }
        });
    }
    //初始化数据
    private void initView() {
        update_back = findViewById(R.id.update_back);
        update_getman2 = findViewById(R.id.update_getman2);
        update_phone2 = findViewById(R.id.update_phone2);
        update_area2 = findViewById(R.id.update_area2);
        update_name2 = findViewById(R.id.update_name2);
        update_default = findViewById(R.id.update_default);
        update_save = findViewById(R.id.update_save);
        update_delete = findViewById(R.id.update_delete);
        update_location = findViewById(R.id.update_location);

        //将原来的数据打印出来
        update_getman2.setText(addressItem.getGetman());
        update_phone2.setText(addressItem.getPhone());
        update_area2.setText(addressItem.getArea());
        update_name2.setText(addressItem.getName());

       //获取地址id
        id = addressItem.getId();
        //获取用户id
        user_id = (int) SharedPreferencesUtil.get(this,"userInfo","user_id",7);
    }
  //修改保存
    public void UpAddress() {
        if (!validate()) {
            UpdateAddressFailed();
            return;
        }
        String update_area = update_area2.getText().toString();
        String update_name = update_name2.getText().toString();
        String update_getman = update_getman2.getText().toString();
        String update_phone = update_phone2.getText().toString();

        postAddAddressRequest(update_area,update_name,update_getman,update_phone);
    }
  //post请求来获得数据
    private void postAddAddressRequest(String area, String name,String getman,String phone) {
        //将数据传给后端
        RequestBody body = new FormBody.Builder()
                .add("id",String.valueOf(id))
                .add("user_id",String.valueOf(user_id))
                .add("area", area)
                .add("name", name)
                .add("getman",getman)
                .add("is_default",String.valueOf(flag))
                .add("phone", phone).build();

        //发送修改请求
        NetUtil.doPost(Constants.BASE_URL + Constants.UPDATE_AddressById_URL + id, body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = -1;
                mHandler.sendMessage(message);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                Message message = Message.obtain();
                //获取返回结果
                String result = response.body().string().trim();
                Log.d("result",result);
                try {
                    JSONObject json = JSON.parseObject(result);
                    if (json.getInteger("status")==0) {
                        message.what = 1;
                    } else {
                        message.what = 0;
                    }
                } catch (Exception e) {
                    Log.e("network error!", e.getMessage());
                    message.what = 0;
                    message.obj = "请求响应失败！";
                }
                mHandler.sendMessage(message);
            }
        });
    }
    //删除地址
    private void Delete() {
        String url = Constants.BASE_URL + Constants.DELETE_AddressById_URL + id;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        Log.d("result",result);
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            message.what = 1;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //修改地址handler
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    UpdateAddressSuccess();
                    break;
                default:
                    UpdateAddressFailed();
                    break;
            }
        }
    };

    //删除地址handler
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    DeleteAddressSuccess();
                    break;
                default:
                    DeleteAddressFailed();
                    break;
            }
        }
    };
    //修改地址
    public boolean validate() {
        boolean valid = true;
        String area1 = update_area2.getText().toString();
        String name1 = update_name2.getText().toString();
        String getman1 = update_getman2.getText().toString();
        String phone1 = update_phone2.getText().toString();

        //收货人错误
        if (TextUtils.isEmpty(getman1)) {
            update_getman2.setError("收货人不能为空");
            valid = false;
        } else if (getman1.length()>5){
            update_getman2.setError("昵称长度不得超过5，请修改！");
            valid = false;
        }
        //手机号码错误
        if (phone1.isEmpty()) {
            update_phone2.setError("请输入电话号码！");
            valid = false;
        } else if(!(phone1.length()==11)){
            update_phone2.setError("请输入11位正确的手机号码");
            valid = false;
        }
        //所在地区错误
        if (TextUtils.isEmpty(area1)) {
            update_area2.setError("收货人不能为空");
            valid = false;
        }
        //详细地址错误
        if (TextUtils.isEmpty(name1)) {
            update_name2.setError("收货人不能为空");
            valid = false;
        }
        return valid;
    }
    //修改地址成功
    public void UpdateAddressSuccess() {
        Toast.makeText(this, "修改地址成功!", Toast.LENGTH_SHORT).show();
        update_save.setEnabled(true);
        //更新sp数据
        SharedPreferences sharedPreferences = getSharedPreferences("addressInfo", Context.MODE_PRIVATE); //私有数据
        //保存用户信息
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("addressArea", addressArea);
        editor.putString("addressName", addressName);
        editor.commit();//提交修改


        finish();
    }
    //修改地址失败
    public void UpdateAddressFailed() {
        Toast.makeText(getBaseContext(), "修改失败", Toast.LENGTH_LONG).show();
        update_save.setEnabled(true);
    }

    //删除地址成功
    public void DeleteAddressSuccess() {
        Toast.makeText(this, "删除地址成功!", Toast.LENGTH_SHORT).show();

        finish();
    }
    //删除地址失败
    public void DeleteAddressFailed() {
        Toast.makeText(getBaseContext(), "删除失败", Toast.LENGTH_LONG).show();
    }

    public void getLocation(){
        //获取定位
        TencentLocationManager mLocationManager = TencentLocationManager.getInstance(mContext);
        mLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        update_area2.setText(tencentLocation.getAddress());
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }
}